﻿using Markdig;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LPBToolsNF
{
    public partial class WMarkDownFB : UserControl
    {
        private bool _webViewInitialized = false;
        public WMarkDownFB()
        {
            InitializeComponent();
            // 在设计时禁用 WebView2 初始化
            if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
            {
                webView2MDInfo.Visible = false;
                return;
            }
            InitializeWebView2Async();
        }

        private async void InitializeWebView2Async()
        {
            try
            {
                // 确保WebView2已初始化
                if (webView2MDInfo.CoreWebView2 == null)
                {
                    // 确保环境已初始化
                    if (!WebView2EnvironmentManager.Instance.IsInitialized)
                        await WebView2EnvironmentManager.Instance.InitializeAsync();
                    await webView2MDInfo.EnsureCoreWebView2Async(WebView2EnvironmentManager.Instance.Environment);
                }
                // 加载基础HTML模板
                string baseHtml = GenerateBaseHtml(this.BackColor);
                webView2MDInfo.NavigateToString(baseHtml);

                // 初始化完成标记
                _webViewInitialized = true;
                // 初始化WebView2消息处理
                webView2MDInfo.CoreWebView2.NavigationStarting += CoreWebView2_NavigationStarting;

                // 首次同步背景色
                UpdateWebViewBackgroundColor(this.BackColor);
                UpdateLineSpacing(_lineSpacing);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化WebView2时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public Color BackColor_MDBox
        {
            get { return this.BackColor; }
            set
            {
                if (this.BackColor != value)
                {
                    this.BackColor = value;
                    UpdateWebViewBackgroundColor(value);
                }
            }
        }
        private void UpdateWebViewBackgroundColor(Color backColor)
        {
            if (webView2MDInfo.CoreWebView2 != null)
            {
                string colorCode = $"rgb({backColor.R}, {backColor.G}, {backColor.B})";
                string script = $"document.body.style.backgroundColor = '{colorCode}';";
                webView2MDInfo.CoreWebView2.ExecuteScriptAsync(script);
            }
        }

        private string GenerateBaseHtml(Color backColor)
        {
            string colorCode = $"rgb({backColor.R}, {backColor.G}, {backColor.B})";

            return $@"
<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Markdown实时渲染</title>
    <style>
        :root {{
            --line-spacing: {_lineSpacing}; /* 行间距变量 */
        }}
        
        body, html {{
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }}
        
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background-color: {colorCode};
            line-height: var(--line-spacing)!important; /* 应用行高变量 */
        }}
        
        /* 核心修改：使用flex布局实现内容从底部开始向上增长 */
        #markdownContainer {{
            display: flex;
            flex-direction: column-reverse; /* 内容从底部开始排列 */
            height: 100%;
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: rgba(155, 155, 155, 0.5) transparent;
        }}
        
        /* 自定义滚动条样式 */
        #markdownContainer::-webkit-scrollbar {{
            width: 6px;
        }}
        
        #markdownContainer::-webkit-scrollbar-track {{
            background: transparent;
        }}
        
        #markdownContainer::-webkit-scrollbar-thumb {{
            background-color: rgba(155, 155, 155, 0.5);
            border-radius: 20px;
        }}
        
        .markdown-line {{
            opacity: 0;
            transform: translateY(10px);
            transition: opacity 0.3s ease, transform 0.3s ease;
            margin: 0;/* 移除默认间距 */
        }}

        /* 改进列表样式处理 */
        .markdown-line ul, .markdown-line ol {{
            margin-top: 0;
            margin-bottom: 0;
            padding-left: 20px;
        }}
        
        .markdown-line p {{
            margin: 0; /* 移除段落间距 */
        }}

        .visible {{
            opacity: 1;
            transform: translateY(0);
        }}
        
        /* 通用代码块样式（不区分语言） */
        pre {{
            background-color: #111;
            color: #EEE;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            overflow-x: auto;
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
            font-size: 0.9em;
        }}
        
        code {{
            color: #333;
            background-color: #f8f8f8;
            border-radius: 3px;
            padding: 0.1em 0.3em;
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
        }}
        
        pre code {{
            padding: 0;
            background: none;
            border: none;
            color: inherit;
        }}
    </style>
</head>
<body>
    <div id='markdownContainer'>
        <!-- Markdown内容将在这里动态添加 -->
    </div>

    <script>
        // 内容容器引用
        const container = document.getElementById('markdownContainer');
        
        // 标记用户是否手动滚动
        let userHasScrolled = false;
        
        // 监听滚动事件，检测用户是否手动滚动
        container.addEventListener('scroll', () => {{
            userHasScrolled = container.scrollTop !== 0;
        }});
        
        // 追加Markdown行的函数
        function appendMarkdownLine(html) {{

            console.log('appendMarkdownLine'); 
            // 创建新元素
            const newElement = document.createElement('div');
            newElement.className = 'markdown-line';
            newElement.innerHTML = html;
            
            // 添加到容器顶部（因为是column-reverse布局，实际显示在底部）
            container.insertBefore(newElement, container.firstChild);
            
            // 触发动画
            setTimeout(() => {{
                newElement.classList.add('visible');
                
                // 如果用户没有手动滚动，保持在底部
                if (!userHasScrolled) {{
                    scrollToBottom();
                }}
            }}, 50);
        }}
        
        // 滚动到底部的函数（在column-reverse布局中，滚动到顶部实际上是内容底部）
        function scrollToBottom() {{
            container.scrollTop = 0;
        }}
        
        // 重置内容
        function resetContent() {{
            container.innerHTML = '';
            userHasScrolled = false;
            scrollToBottom();
        }}
        
        // 页面加载完成后滚动到底部
        document.addEventListener('DOMContentLoaded', () => {{
            scrollToBottom();
        }});       
        
    </script>
</body>
</html>";
        }

        // 处理导航事件，拦截本地文件链接
        private void CoreWebView2_NavigationStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
        {
            string uri = e.Uri.ToLower();

            // 检查是否是本地文件链接
            if (uri.StartsWith(WMarkDownBox.uriLocalFileHeader))
            {
                // 取消默认导航
                e.Cancel = true;

                try
                {
                    // 转换为本地文件路径
                    string localPath = uri.Replace(WMarkDownBox.uriLocalFileHeader, "");

                    // 处理空格和特殊字符
                    localPath = System.Web.HttpUtility.UrlDecode(localPath);

                    // 使用系统默认程序打开文件
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = localPath,
                        UseShellExecute = true
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无法打开文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            if (uri.StartsWith("http"))
            {
                // 取消默认导航
                e.Cancel = true;
            }
        }

        public decimal LineSpacing
        {
            get { return _lineSpacing; }
            set
            {
                if (value > 0.2m)
                    UpdateLineSpacing(value);
            }
        }

        decimal _lineSpacing = 1.5m;
        private void UpdateLineSpacing(decimal spacing)
        {
            _lineSpacing = spacing;
            if (webView2MDInfo.CoreWebView2 != null)
            {
                string script = $"document.documentElement.style.setProperty('--line-spacing', '{_lineSpacing}');";
                webView2MDInfo.CoreWebView2.ExecuteScriptAsync(script);
            }
        }

        // 接收新的Markdown行并追加显示
        public void AppendMarkdownLine(string markdownLine)
        {
            this.Invoke(new Action(() =>
            {
                try
                {
                    if (!_webViewInitialized) return;
                    // 转换 Markdown 并保存为 HTML
                    var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions()
                        .UseSyntaxHighlighting()  // 启用语法高亮
                        .Build();
                    string htmlLine = Markdown.ToHtml(markdownLine, pipeline);

                    // 注入到WebView2
                    string escapedHtml = EscapeJsString(htmlLine);
                    string script = $"appendMarkdownLine('{escapedHtml}');";
                    webView2MDInfo.CoreWebView2.ExecuteScriptAsync(script);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"渲染Markdown行时出错: {ex.Message}");
                }
            }));
        }

        // 重置显示内容
        public void ResetDisplay()
        {
            this.Invoke(new Action(() =>
            {
                if (!_webViewInitialized) return;
                webView2MDInfo.CoreWebView2.ExecuteScriptAsync("resetContent();");
            }));
        }

        // 安全转义JavaScript字符串，避免引号问题
        private string EscapeJsString(string input)
        {
            if (string.IsNullOrEmpty(input))
                return "";
            // 修复转义逻辑，正确处理各种特殊字符
            return input
                .Replace("\\", "\\\\")
                .Replace("'", "\\'")
                .Replace("\n", "\\n")
                .Replace("\r", "\\r")
                .Replace("\"", "\\\"")
                .Replace("`", "\\`");
        }

        private void webView2MDInfo_WebMessageReceived(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs e)
        {
            Console.WriteLine($"WebView2 console log: {e.WebMessageAsJson}");
        }
    }
}
